package jjn.round1;

/**
 * @author Jjn
 * @since 2022/8/21 14:42
 */
public class LeetCode557_ReverseWordsInAString {
    public String reverseWords(String s) {
        int slow = 0, fast = 0, max = s.length();
        char[] chars = s.toCharArray();
        while (fast < max) {
            if (chars[fast] == ' ' && chars[slow] == ' ') {
                fast++;
                slow++;
            }
            while (fast < max && chars[fast] != ' ') {
                fast++;
            }
            reverseWord(chars, slow, fast);
            slow = fast;
        }
        return new String(chars);
    }

    private void reverseWord(char[] chars, int start, int end) {
        if (chars == null || chars.length == 0) {
            return;
        }
        int left = start, right = end - 1;
        while (left < right) {
            char temp = chars[right];
            chars[right] = chars[left];
            chars[left] = temp;
            left++;
            right--;
        }
    }
}
